package com.sgb.capital.view.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.sgb.capital.R;
import com.sgb.capital.base.BaseActivity;
import com.sgb.capital.callback.Constants;
import com.sgb.capital.callback.ZMessageEvent;
import com.sgb.capital.databinding.ActivityOpenAccountBinding;
import com.sgb.capital.model.BusinessInfoByCompanyEntity;
import com.sgb.capital.model.OpenBusinessBean;
import com.sgb.capital.utils.Utils;
import com.sgb.capital.utils.ZGlideEngine;
import com.sgb.capital.view.pop.CutPop;
import com.sgb.capital.view.pop.SeeBigPicture;
import com.sgb.capital.view.pop.SelectAlbumPop;
import com.sgb.capital.view.pop.TipPop;
import com.sgb.capital.view.widget.MToast;
import com.sgb.capital.viewmodel.OpenAccountModel;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.List;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import razerdp.basepopup.BasePopupWindow;


public class OpenAccountActivity extends BaseActivity {

    private OpenAccountModel model;
    private ActivityOpenAccountBinding mBinding;
    private SelectAlbumPop pop;
    private SeeBigPicture seeBigPicture;
    private int Type = 0;
    private TipPop mTipPop;

    OpenBusinessBean mOpenBusinessBean = new OpenBusinessBean();

    public static void start(Context context) {
        Intent intent = new Intent(context, OpenAccountActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        mTipPop = new TipPop(mContext, "", "恭喜您，资料提交成功请等待审核", "", "知道了");
        EventBus.getDefault().register(this);
        model = new ViewModelProvider(this).get(OpenAccountModel.class);
        Utils.setStatusBarLightMode(this, true);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_open_account);
        mBinding.licenceOpenAccounts.setOnClickListener(v -> showPop(1));
        mBinding.identityCardPhoneImg.setOnClickListener(v -> showPop(2));
        mBinding.identityCardBackImg.setOnClickListener(v -> showPop(3));
        mBinding.samplePictures.setOnClickListener(v -> seeBigPicture.showPop(1, mBinding.grayLayout));
        mBinding.samplePictures1.setOnClickListener(v -> seeBigPicture.showPop(2, mBinding.grayLayout));
        mBinding.samplePictures2.setOnClickListener(v -> seeBigPicture.showPop(3, mBinding.grayLayout));
        pop = new SelectAlbumPop(this);
        seeBigPicture = new SeeBigPicture(this);
        pop.setBgView(mBinding.grayLayout);
        seeBigPicture.setBgView(mBinding.grayLayout);
        pop.setOnResultClick((key1, key2, key3) -> openAlbum());
        model.infoByCompanyEntityMutableLiveData.observe(this, businessInfoByCompanyEntity -> setData());
        model.stringMutableLiveData.observe(this, Pic -> {
            if (Type == 1) {
                if (TextUtils.isEmpty(model.stringMutableLiveData.getValue()))
                    mBinding.licenceOpenAccounts.setImageResource(R.color.transparent);
                else
                    mOpenBusinessBean.bankAccountLicence = Pic;
            } else if (Type == 2) {
                if (TextUtils.isEmpty(model.stringMutableLiveData.getValue()))
                    mBinding.identityCardPhoneImg.setImageResource(R.color.transparent);
                else
                    mOpenBusinessBean.idCardFront = Pic;
            } else {
                if (TextUtils.isEmpty(model.stringMutableLiveData.getValue()))
                    mBinding.identityCardBackImg.setImageResource(R.color.transparent);
                else
                    mOpenBusinessBean.idCardBack = Pic;
            }
        });
    }

    @Override
    public void initData() {
        model.getBusinessCompanyInfo(this);
    }

    private void setData() {
        if (model.infoByCompanyEntityMutableLiveData.getValue() == null) return;
        BusinessInfoByCompanyEntity entity = model.infoByCompanyEntityMutableLiveData.getValue();
        if (!TextUtils.isEmpty(entity.license))
            Glide.with(mContext).load(entity.license).into(mBinding.businessLicense);
        if (!TextUtils.isEmpty(entity.bankAccountLicence))
            Glide.with(mContext).load(entity.bankAccountLicence).into(mBinding.licenceOpenAccounts);
        if (!TextUtils.isEmpty(entity.idCardFront))
            Glide.with(mContext).load(entity.idCardFront).into(mBinding.identityCardPhoneImg);
        if (!TextUtils.isEmpty(entity.idCardBack))
            Glide.with(mContext).load(entity.idCardBack).into(mBinding.identityCardBackImg);
        mBinding.nameCompany.setText(entity.name);
        mBinding.businessAddress.setText(entity.address);
        mBinding.IDType.setText("营业执照");
        mBinding.creditCode.setText(entity.creditCode);
        mOpenBusinessBean.bussinessLicense = entity.license;
        if (!TextUtils.isEmpty(entity.legalName))
            mBinding.name.setText(entity.legalName);
        if (!TextUtils.isEmpty(entity.identityId))
            mBinding.ID.setText(entity.identityId);
        if (!TextUtils.isEmpty(entity.contactsName))
            mBinding.businessName.setText(entity.contactsName);
        if (!TextUtils.isEmpty(entity.mobileId))
            mBinding.businessTel.setText(entity.mobileId);
    }

    private void saveData() {
        if (mBinding.llShow.getVisibility() == View.VISIBLE) {
            if (TextUtils.isEmpty(mOpenBusinessBean.bankAccountLicence)) {
                MToast.showToast(mContext, "请上传资质证明");
                return;
            }
        }
        if (Utils.isEmpty(mBinding.name.getText().toString())) {
            MToast.showToast(mContext, "请输入法人姓名");
            return;
        }
        if (TextUtils.isEmpty(mBinding.ID.getText().toString())) {
            MToast.showToast(mContext, "请输入法人身份证号");
            return;
        }
        if (!Utils.idCardValidate(mBinding.ID.getText().toString())) {
            MToast.showToast(Utils.getContext(), "身份证号格式错误");
            return;
        }
        if (TextUtils.isEmpty(mOpenBusinessBean.idCardFront)) {
            MToast.showToast(mContext, "请上传身份证正面图片");
            return;
        }
        if (TextUtils.isEmpty(mOpenBusinessBean.idCardBack)) {
            MToast.showToast(mContext, "请上传身份证反面图片");
            return;
        }
        if (TextUtils.isEmpty(mBinding.businessName.getText().toString())) {
            MToast.showToast(mContext, "请输入业务联系人姓名");
            return;
        }
        if (TextUtils.isEmpty(mBinding.businessTel.getText().toString())) {
            MToast.showToast(mContext, "请输入业务联系人手机号");
            return;
        } else if (!Utils.isChinaPhoneLegal(mBinding.businessTel.getText().toString())) {
            MToast.showToast(this, "手机号格式错误");
            return;
        }
        mBinding.okView.setEnabled(false);
        mOpenBusinessBean.address = mBinding.businessAddress.getText().toString();
        mOpenBusinessBean.certId = mBinding.creditCode.getText().toString();
        mOpenBusinessBean.contactsName = mBinding.businessName.getText().toString();
        mOpenBusinessBean.identityId = mBinding.ID.getText().toString();
        mOpenBusinessBean.legalName = mBinding.name.getText().toString();
        mOpenBusinessBean.mobileId = mBinding.businessTel.getText().toString();
        mOpenBusinessBean.subMerAlias = mBinding.nameCompany.getText().toString();
        mOpenBusinessBean.subMerName = mBinding.nameCompany.getText().toString();
        mOpenBusinessBean.subMerType = mBinding.tvTip.getText().toString().contains("企业商户") ? "3" : "2";
        model.preAudit(mOpenBusinessBean, mContext);
    }

    private void openAlbum() {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .imageEngine(ZGlideEngine.createGlideEngine())
                .maxSelectNum(1)
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(List<LocalMedia> result) {
                        File file = new File(result.get(0).getRealPath());
                        model.uploadMutiFileModel(file, 1, OpenAccountActivity.this);
                        if (Type == 1) {
                            Glide.with(mContext).load(result.get(0).getRealPath()).into(mBinding.licenceOpenAccounts);
                        } else if (Type == 2) {
                            Glide.with(mContext).load(result.get(0).getRealPath()).into(mBinding.identityCardPhoneImg);
                        } else {
                            Glide.with(mContext).load(result.get(0).getRealPath()).into(mBinding.identityCardBackImg);
                        }
                        pop.dismiss();
                    }

                    @Override
                    public void onCancel() {
                    }
                });
    }

    // TODO: 2021/5/31 0031
    @Override
    public void initListener() {
        mBinding.ivBack.setOnClickListener(v -> finish());
        mBinding.okView.setOnClickListener(v -> saveData());
        mTipPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                finish();
            }
        });
        mBinding.llCut.setOnClickListener(v -> new CutPop(this).show());
    }

    private void showPop(int type) {
        Type = type;
        if (!pop.isShowing()) {
            pop.showDownPopwindow(mBinding.grayLayout, true);
        }
    }

    @Subscribe
    public void getCode(ZMessageEvent event) {
        switch (event.code) {
            case Constants.ACTIVATE:
                mBinding.okView.setEnabled(true);
                break;
            case Constants
                    .EVENT_REFRESH:
                mTipPop.show();
                break;
            case Constants
                    .EVENT_SELECT:
                mBinding.tvTip.setText((String) event.data);
                mBinding.llShow.setVisibility(mBinding.tvTip.getText().toString().contains("企业商户") ? View.VISIBLE : View.GONE);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}